//
//  WBUserAccountViewModel.swift
//  SinaWeibo
//
//  Created by 风不会停息 on 2016/11/16.
//  Copyright © 2016年 风不会停息. All rights reserved.
//

import UIKit


import SVProgressHUD
//单例对象，全局只有一个对象来管理一个账号，每次用户注销的时候清楚缓存信息
//作用
/*
 1.封装数据逻辑的处理
 2.封装网络请求
 
 */
class WBUserAccountViewModel: NSObject {

    
    //单例的创建
    static let WBUserAccountShared = WBUserAccountViewModel()
    //视图模型需要引用用户的模型对象,需要用模型对象来处理数据逻辑
    var account:WBAccount?
    
    override init() {
        super.init()
        //将磁盘数据保存到内存中,保证登录的时候不在访问磁盘
        account = loaduserInfo()
    }
    
    var headURL: URL? {
        return URL(string: account?.avatar_large ?? "")
        
    }
    
    //定义一个变量来保存用户是否登录
    var isloginIN:Bool{
        //令牌不为空 &&令牌没有过期
        if account?.access_token != nil && isExpires == true {
            return true
        }
        return false
        
        
    }
    //判断令牌是否过期
    var isExpires:Bool{
        
        //对比当前时间看是否过期
        if account?.expires_date?.compare(Date()) == ComparisonResult.orderedAscending {
            return false
        }
        return true
    }
    var access_token: String? {
        return account?.access_token
    }
    
    func loadAccessToken(code:String,finished:@escaping (Bool)->()){
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : "2483618679",
                          "client_secret" : client_secret,
                          "grant_type" : "authorization_code",
                          "code" : code,
                          "redirect_uri" : redirect_uri]
        
        WBNetWorkTools.tool.request(method: .POST, urlString: urlString, parameter: parameters) { (responseObject, error) in
            if error != nil{
                print(error)
                finished(false)
                return
            }else {
                //                print(responseObject)
                
                ///这个地方？？？
                self.loadUserInfo(dict: responseObject as! [String:Any],loadUserInfoFinished: finished)
            }
        }
        
    }
    private func loadUserInfo(dict:[String:Any],loadUserInfoFinished:@escaping (Bool)->()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let token = dict["access_token"]
        let uid = dict["uid"]
        let parameter = ["access_token":token,
                         "uid":uid]
        WBNetWorkTools.tool.request(method: .GET, urlString: urlString, parameter: parameter) { (responseObject, error) in
            if error != nil{
                print(error!)
                SVProgressHUD.showError(withStatus: "出错啦")
                loadUserInfoFinished(false)
            }
            //            print(responseObject!)
            //将用户信息存储在本地
            //需要将授权之后的得到的字典和用户信息字典合并 之后再存储？？？？？
            ///???????
            var userInfoDict = responseObject as! [String:Any]
            for(key,value) in dict{
                userInfoDict[key] = value
            }
            ///
            let userAccount = WBAccount(dict: userInfoDict)
            self.saveuserInfoAccount(userInfo: userAccount)
            //            print(userAccount.name)
            
            //如果不写的话，首次登录的时候会有bug
            self.account = userAccount
            //为什么是这个地方登陆0.0
            loadUserInfoFinished(true)
        }
        
    }
    private func saveuserInfoAccount(userInfo:WBAccount){
        
        //需要将用户的信息放到document文件夹中，才能自动备份到icloud，放在temp或者cache中会被清除
        
        //会出现崩溃
        NSKeyedArchiver.archiveRootObject(userInfo, toFile: plistPath)
        print(plistPath)
        
    }
    //返回值应该是一个可选类型，因为可能读取不到用户的数据
     func loaduserInfo() -> WBAccount?{
        
        let account = NSKeyedUnarchiver.unarchiveObject(withFile: plistPath)
        if let userAccount = account as? WBAccount {
            return userAccount
        }
        return nil
    }

    
    
}
